package com.dayou.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class LogUtil {
    @Value("${logpath}")
    private String logPath;
    private File logFile;
    @Autowired
    private SimpleDateFormat simpleDateFormat;
    public void log(String logMsg,LOG_TYPE logType) {
        try {
            createLogFile();
            Date date = new Date();
            String dateStr = simpleDateFormat.format(date);
            FileWriter fw = new FileWriter(logFile, true);

            String logText = String.format("[%s]%s： %s", dateStr,logType,logMsg);
            System.out.println(logText);
            fw.append(logText+"\r\n");
            fw.flush();
            fw.close();
        } catch (IOException e) {
            System.out.println("日志写入失败。");
            System.out.println(e.getMessage());
        }
    }

    public void debug(String logMsg){
        log(logMsg,LOG_TYPE.DEBUG);
    }
    public void info(String logMsg){
        log(logMsg,LOG_TYPE.INFO);
    }
    public void warn(String logMsg){
        log(logMsg,LOG_TYPE.WARN);
    }
    public void error(String logMsg){
        log(logMsg,LOG_TYPE.ERROR);
    }

    private void createLogFile(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH");
        String dateStr = sdf.format(date);
        logFile = new File(logPath + "log" + dateStr + ".log");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                System.out.println("文件创建失败。");
                System.out.println(e.getMessage());
            }
        }
    }

    public enum LOG_TYPE{
        DEBUG,INFO,WARN,ERROR
    }
}
